package com.example.demo.service.impl;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    // 用户数据存储
    private final Map<Long, User> userMap = new ConcurrentHashMap<>();
    // ID生成器
    private final AtomicLong idGenerator = new AtomicLong(1);

    @Override
    public List<User> findAllUsers() {
        return new ArrayList<>(userMap.values());
    }

    @Override
    public User findUserById(Long id) {
        User user = userMap.get(id);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + id);
        }
        return user;
    }

    @Override
    public User saveUser(User user) {
        if (user.getId() == null) {
            // 新建用户
            user.setId(idGenerator.getAndIncrement());
        } else {
            // 确保用户存在
            if (!userMap.containsKey(user.getId())) {
                throw new RuntimeException("用户不存在: " + user.getId());
            }
        }
        userMap.put(user.getId(), user);
        return user;
    }

    @Override
    public void deleteUser(Long id) {
        if (userMap.remove(id) == null) {
            throw new RuntimeException("用户不存在: " + id);
        }
    }

    // 根据名字搜索用户
    @Override
    public List<User> findUsersByName(String name) {
        return userMap.values().stream()
                .filter(user -> user.getName() != null && 
                              user.getName().contains(name))
                .collect(Collectors.toList());
    }

    // 检查邮箱是否已存在
    @Override
    public boolean isEmailExists(String email, Long excludeId) {
        return userMap.values().stream()
                .anyMatch(user -> user.getEmail().equals(email) && 
                                !user.getId().equals(excludeId));
    }
} 